//
//  CNNavMarketViewController.m
//  BeeQuick_19
//
//  Created by kimi on 16/9/23.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNNavMarketViewController.h"
#import "CNDetailSearchViewController.h"


static NSString * const reuseIdentifier = @"hotSearchCell";

@interface CNNavMarketViewController ()<UISearchBarDelegate>

@property (nonatomic,weak)UILabel *HotLabel;
@property (nonatomic,weak)UILabel *historyLabel;
@property (nonatomic,weak) UICollectionView *collectionView;

@property (strong, nonatomic) SKTagView *tagView;
@property (strong, nonatomic) SKTagView *historyTagView;
@property (strong, nonatomic) NSArray *colors;

//热门搜索内容的数组
@property (nonatomic,strong) NSArray *hotSearchArray;
//获取搜索栏
@property (nonatomic,weak)UISearchBar *searchBar;
//搜索内容
@property (nonatomic,copy) NSString *searchInfo;
//历史搜索记录数组
@property (nonatomic,strong) NSMutableArray *HistorySearchArray;
//记录手势
@property (nonatomic,strong) UITapGestureRecognizer *tap;

@end

@implementation CNNavMarketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self loadData];
    
    [self setupUI];
    
    self.view.backgroundColor = [UIColor whiteColor];
    //初始化数组
    self.HistorySearchArray = [NSMutableArray array];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 加载数据
- (void)loadData{
    
}

#pragma mark - 设置UI
- (void)setupUI
{
    //设置statbar背景

    //设置搜索栏
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barBuutonItemWithTarget:self action:@selector(backButtonClick) icon:@"v2_goback" highlighticon:@"v2_goback"];
    
    UISearchBar *searchBar = [UISearchBar new];
    searchBar.placeholder = @"请输入搜索内容";
    searchBar.delegate = self;
    self.searchBar = searchBar;
    self.navigationItem.titleView = searchBar;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.view.userInteractionEnabled =YES;
    //添加搜索栏右侧button
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(searchInfoFromNet)];
    
    //设置颜色
    item.tintColor = [UIColor blueColor];
    
    self.navigationItem.rightBarButtonItem = item;
    //设置字体颜色
 
    //添加背景，产生1像素的线
    UIView *backView = [UIView new];
    backView.backgroundColor = [UIColor colorWithHex:0xEFEFEF];
    [self.view addSubview:backView];
    
    //布局
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(22);
        make.left.right.offset(0);
        make.height.offset(43);
    }];
    
    //添加热门搜索label
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
    label.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:label];
    self.HotLabel = label;
    
    label.text = @"热门搜索";
    [label setTextColor:[UIColor darkGrayColor]];
    
    //布局
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backView.mas_bottom).offset(20);
        make.left.offset(8);
        make.height.offset(20);
    }];
    
    //添加历史搜索label
    UILabel *historyLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    historyLabel.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:historyLabel];
    
    historyLabel.text = @"历史搜索";
    [historyLabel setTextColor:[UIColor darkGrayColor]];
    self.historyLabel = historyLabel;
    historyLabel.hidden = true;
    
    //设置热门标签
    [self setupTagView];
    
    //布局历史搜索Label
    [historyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tagView.mas_bottom).offset(8);
        make.left.offset(8);
        make.height.offset(20);
    }];
    
    //设置历史标签
    [self setupHistoryTagView];
    
    
    //添加清点手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tipGestureRecognizer:)];
    self.tap = tap;
    [self.tagView addGestureRecognizer:tap];
    [self.historyTagView addGestureRecognizer:tap];
    
}
- (void)tipGestureRecognizer:(UIGestureRecognizer *)tap{
    
    [self.searchBar resignFirstResponder];
}
#pragma mark - Private
- (void)setupTagView {
    self.tagView = ({
        SKTagView *view = [SKTagView new];
        view.backgroundColor = [UIColor whiteColor];
        view.padding = UIEdgeInsetsMake(5, 10, 5, 10);
        view.interitemSpacing = 10;
        view.lineSpacing = 10;
        view.didTapTagAtIndex = ^(NSUInteger index){
            //处理点击事件
            //1.选获取选中的index
            //2.获取当前数组中的String
            NSString *searchName = self.hotSearchArray[index];
            //3.将string设置searchBar
            self.searchBar.text = searchName;
            self.searchInfo = searchName;
        };
        view;
    });
    
    [self.view addSubview:self.tagView];
    [self.tagView mas_makeConstraints: ^(MASConstraintMaker *make) {
        make.top.equalTo(self.HotLabel.mas_bottom).offset(8);
        make.left.right.offset(0);
    }];
    
    //懒加载数据
     [self hotSearchArray];
}

- (void)setupHistoryTagView {
    self.historyTagView = ({
        SKTagView *view = [SKTagView new];
        view.backgroundColor = [UIColor whiteColor];
        view.padding = UIEdgeInsetsMake(5, 10, 5, 10);
        view.interitemSpacing = 10;
        view.lineSpacing = 10;
        
        view.didTapTagAtIndex = ^(NSUInteger index){
            //处理点击事件
            //1.选获取选中的index
            //2.获取当前数组中的String
            NSString *searchName = self.HistorySearchArray[index];
            NSLog(@"%@",searchName);
            //3.将string设置searchBar
            self.searchBar.text = searchName;
            self.searchInfo = searchName;
        };
        view;
    });
    
    //自动布局
    [self.view addSubview:self.historyTagView];
    [self.historyTagView mas_makeConstraints: ^(MASConstraintMaker *make) {
        make.top.equalTo(self.historyLabel.mas_bottom).offset(8);
        make.size.equalTo(self.tagView);
        make.bottom.offset(0);
    }];
    
    
}

//添加内容
- (void)hideTabBar {
    if (self.tabBarController.tabBar.hidden == YES) {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
    
}

#pragma mark - 返回按钮
- (void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark - 根据内容搜索数据
- (void)searchInfoFromNet
{
    [self.searchBar endEditing:YES];
    
    CNDetailSearchViewController *vc = [[CNDetailSearchViewController alloc]init];
    
    //回调刷新界面数据
    vc.searchInfoBlock = ^(NSString *searchString){
        //如果搜索的值是空的直接返回
        if (searchString == nil || [searchString containsString:@" "]||[searchString isEqualToString:@""]) {
            return ;
        }
        self.searchInfo = searchString;
        self.searchBar.text = searchString;
        [self.HistorySearchArray insertObject:self.searchInfo atIndex:0];
        [self addHistoryTag];
        
    };
    vc.hidesBottomBarWhenPushed = false;
    vc.searchInfoString = self.searchInfo;
    vc.searchFlag = true;


    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark - 代理

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    self.searchInfo = searchBar.text;
}

#pragma mark - 加载数据
-(NSArray *)hotSearchArray
{
    if (_hotSearchArray == nil) {
        _hotSearchArray = [NSArray array];
        //1.组包参数
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        
        [param setValue:@"6" forKey:@"call"];
        
        //网络获取数据
        [[CNHTTPSessionManager sharedManager] request:CNHttpMethodPost componentUrlString:@"search.json.php" parameters:param completion:^(id response, NSError *error) {
            if (error != nil || response == nil ) {
                NSLog(@"请求错误%@",error);
                return;
            }else{
                NSArray *array = response[@"data"][@"hotquery"];
                
                self.hotSearchArray = [NSArray arrayWithArray:array];
                [self.hotSearchArray enumerateObjectsUsingBlock: ^(NSString *text, NSUInteger idx, BOOL *stop) {
                    SKTag *tag = [SKTag tagWithText: text];
                    tag.textColor = [UIColor whiteColor];
                    tag.fontSize = 15;
                    //tag.font = [UIFont fontWithName:@"Courier" size:15];
                    //tag.enable = NO;
                    tag.padding = UIEdgeInsetsMake(13.5, 12.5, 13.5, 12.5);
                    tag.bgColor = [UIColor randomColor];
                    tag.cornerRadius = 5;
                    [self.tagView addTag:tag];

                }];
                
            }
        }];

    }
    return _hotSearchArray;
}


#pragma mark - 添加历史条目
- (void)addHistoryTag{
    if (self.searchInfo == nil || [self.searchInfo isEqualToString:@" "]) {
        return;
    }
    SKTag *tag = [SKTag tagWithText: self.searchInfo];
    tag.textColor = [UIColor whiteColor];
    tag.fontSize = 15;
    tag.enable = YES;
    tag.padding = UIEdgeInsetsMake(13.5, 12.5, 13.5, 12.5);
    tag.bgColor = [UIColor randomColor];
    tag.cornerRadius = 5;
    
    //设置显示历史
    self.historyLabel.hidden = false;
    
    
    [self.historyTagView insertTag:tag atIndex:0];
}


- (void)viewDidDisappear:(BOOL)animated{
    [self.tagView removeGestureRecognizer:self.tap];
    [self.historyTagView removeGestureRecognizer:self.tap];
}

@end
